import { useState, useCallback } from 'react';

interface UseDeleteConfirmOptions {
  /** 删除操作 */
  onDelete: () => Promise<void>;
  /** 删除成功回调 */
  onSuccess?: () => void;
  /** 删除失败回调 */
  onError?: (error: any) => void;
  /** 自定义标题 */
  title?: string;
  /** 自定义内容 */
  content?: React.ReactNode;
}

/**
 * 删除确认的自定义Hook
 */
const useDeleteConfirm = (options: UseDeleteConfirmOptions) => {
  const { onDelete, onSuccess, onError, title, content } = options;
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [currentId, setCurrentId] = useState<string | number | null>(null);

  // 显示确认框
  const showConfirm = useCallback((id?: string | number) => {
    if (id) setCurrentId(id);
    setVisible(true);
  }, []);

  // 隐藏确认框
  const hideConfirm = useCallback(() => {
    setVisible(false);
    setCurrentId(null);
  }, []);

  // 确认删除
  const handleConfirm = useCallback(async () => {
    try {
      setLoading(true);
      await onDelete();
      onSuccess?.();
      hideConfirm();
    } catch (error) {
      onError?.(error);
    } finally {
      setLoading(false);
    }
  }, [onDelete, onSuccess, onError, hideConfirm]);

  return {
    visible,
    loading,
    currentId,
    showConfirm,
    hideConfirm,
    confirmProps: {
      open: visible,
      title,
      content,
      onConfirm: handleConfirm,
      onCancel: hideConfirm,
      confirmLoading: loading,
    },
  };
};

export default useDeleteConfirm; 